package com.rxyb.dfs;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadCallback;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;

@Service
public class FastDfsClient {

    @Autowired
    private FastFileStorageClient storageClient;

    /**
     * 上传
     *
     * @param fileBytes
     * @param fileExtName 扩展名
     * @return dfsKey
     **/
    public String upload2FastDFS(byte[] fileBytes, String fileExtName) {
        String filePath = null;
        StorePath storePath = this.storageClient.uploadFile(new ByteArrayInputStream(fileBytes), fileBytes.length, fileExtName, null);
        if (null == storePath) {
            return null;
        }
        return storePath.getFullPath();
    }

    /**
     * 上传
     *
     * @param localFilePath
     * @param fileExtName   扩展名
     * @return dfsKey
     **/
    public String upload2FastDFS(String localFilePath, String fileExtName) throws FileNotFoundException {
        String filePath = null;
        // 要上传的文件
        File file = new File(localFilePath);
        // 上传并保存图片，参数： 1-上传的文件流 2-文件的大小 3-文件的后缀 4-可以不管他
        StorePath storePath = this.storageClient.uploadFile(new FileInputStream(file), file.length(), fileExtName, null);
        // 带分组的路径
        if (null == storePath) {
            return null;
        }
        return storePath.getFullPath();
    }

    /**
     * 删除
     **/
    public void deleteFromFastDFS(String dfsKey) {
        this.storageClient.deleteFile(dfsKey);
    }

    /**
     * 下载
     *
     * @param dfsKey 文件路径
     * @return 文件字节数据
     * @throws IOException byte[]
     * @Description: 根据文件路径下载文件
     */
    public byte[] downFile(String dfsKey) throws IOException {
        StorePath storePath = StorePath.parseFromUrl(dfsKey);
        return storageClient.downloadFile(storePath.getGroup(), storePath.getPath(), new DownloadCallback<byte[]>() {
            @Override
            public byte[] recv(InputStream ins) throws IOException {
                return org.apache.commons.io.IOUtils.toByteArray(ins);
            }
        });
    }

}
